@file:Suppress("MemberVisibilityCanBePrivate")

package dev.entao.core.render

import dev.entao.base.urlEncoded
import dev.entao.core.*

class RefererRender(context: HttpContext) : Render(context) {
    val url = context.request.referer?.substringBefore('?') ?: error("no referer")
    val paramMap = LinkedHashMap<String, ArrayList<String>>()

    init {
        context.response.contentTypeHtml()
        val map = context.paramMap
        for ((k, ar) in map) {
            paramMap[k] = ArrayList(ar)
        }
    }

    fun clearParams() {
        paramMap.clear()
    }

    fun removeKey(key: String) {
        paramMap.remove(key)
    }

    fun setParam(key: String, value: String) {
        paramMap[key] = arrayListOf(value)
    }

    fun addParam(key: String, value: String) {
        val ls = paramMap[key] ?: ArrayList()
        ls += value
        paramMap[key] = ls
    }

    fun setError(msg: String) {
        paramMap[Sweet.ERROR_MSG] = arrayListOf(msg)
    }

    fun setSuccess(msg: String) {
        paramMap[Sweet.SUCCESS_MSG] = arrayListOf(msg)
    }

    fun setErrorField(name: String?, msg: String = "") {
        val k = name ?: return
        paramMap[Sweet.fieldError(k)] = arrayListOf(msg)
    }

    override fun onSend() {
        val list = ArrayList<String>()
        for ((k, ls) in paramMap) {
            for (s in ls) {
                list += "${k.urlEncoded}=${s.urlEncoded}"
            }
        }
        val query = list.joinToString("&")
        if (query.isEmpty()) {
            context.response.sendRedirect(url)
        } else {
            context.response.sendRedirect("$url?$query")
        }
    }

}

context (OnHttpContext)
fun sendBack(block: RefererRender.() -> Unit) {
    context.sendBack(block)
}

fun HttpContext.sendBack(block: RefererRender.() -> Unit) {
    val p = RefererRender(this)
    p.block()
    p.send()
}